package fr.unice.tinytorrent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import fr.unice.tinytorrent.api.RemoteClient;
import fr.unice.tinytorrent.api.Tracker;


public class DownloadChunks extends Thread {

	private RemoteClient rc;
	private HashValue h;
	private File outputDirectory;
	private HashValue[] chunksHV;
	private ArrayList<File> chunksFiles;
	private List<DownloadChunks> th;
	private Tracker tracker;
	private ClientImpl clientImpl;



	public DownloadChunks(RemoteClient rc,
			HashValue hashValue, File outputDirectory, HashValue[] chunksHV,
			ArrayList<File> chunksFiles, List<DownloadChunks> th, Tracker tracker, ClientImpl clientImpl) {
		super();
		this.rc = rc;
		this.h = hashValue;
		this.outputDirectory = outputDirectory;
		this.chunksHV = chunksHV;
		this.chunksFiles = chunksFiles;
		this.th = th;
		this.tracker = tracker;
		this.clientImpl = clientImpl;
		
		//Securiser l'acces a la liste
		synchronized (th) {
			th.add(this);	
		}
		
	}

	public void run() {
		//Se connecter au client
		try {
			
			//Recuperer l'index
			int chunkIndex = 0;
			while(!h.equals(chunksHV[chunkIndex])){
				chunkIndex++;
			}

			//Recuperer le chunk
			Chunk chunk = rc.leech(h , chunkIndex);
			HashValue hv = new HashValue(chunk.getPayload(), false);
			if(hv.equals(chunksHV[chunkIndex])){

				//Ecrire le chunk sur le disque
				File f = Chunk.write(chunk, outputDirectory);
				chunksFiles.set(chunkIndex, f);
				
				//Ajouter le nouvelle ressource du client au tacker
				tracker.register(hv, clientImpl);
			}
			
			//Securiser l'acces a la liste
			synchronized (th) {
				th.remove(this);
			}
			

		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		
	}

}
